/* 
 * File:   ShortMsgItemDao.cpp
 * Author: bd
 * 
 * Created on March 28, 2011, 7:50 PM
 */

#include "ShortMsgItemDao.hpp"
#include "Database.hpp"
#include "Activity.hpp"

ShortMsgItemDao::ShortMsgItemDao(Database& session) :
Dao(session)
{
}

ShortMsgItemDao::~ShortMsgItemDao()
{
}

void ShortMsgItemDao::getItems(std::vector<ShortMsgItem>& items, int n, int groupId)
{
    int i = 0;
    ShortMsgItem smi;
    int maxXid = -1;
    updateItemsToSelect(groupId, n, maxXid);

    soci::statement st = (session_.session().prepare <<
            "select * from msg_items where xid=:Xid", soci::use(maxXid), soci::into(smi));
    st.execute();

    while (st.fetch() && i < n)
    {
        items.push_back(smi);
        i++;
    }

}

void ShortMsgItemDao::updateItem(const ShortMsgItem& item)
{
    session_.session() << "update msg_items "
            "set status=:status,"
            "retry=:retry, "
            //"last_update=':last_update', "
            //"insert_date=':insert_date', "
            "handler=:handler "
            "where id=:id", soci::use(item);
}

int ShortMsgItemDao::getMaxXid(int groupId)
{
    int maxXid = -1;
    session_.session() << "select max(xid) from msg_items where group_id=:group_id", soci::use(groupId), soci::into(maxXid);
    return maxXid;
}

int ShortMsgItemDao::updateItemsToSelect(int groupId, int n, int &maxXid)
{
    session_.session() << "lock table msg_items read, msg_items as msg_items_w write";
    maxXid = getMaxXid(groupId) + 1;
    session_.session() << "update msg_items as msg_items_w set status=:newStatus, xid=:max_xid, last_update=CURRENT_TIMESTAMP() "
            "where status=:status and group_id=:groupId limit :chunkSize",
            soci::use(static_cast<int> (ShortMsgItem::INPROGRESS)),
            soci::use(maxXid),
            soci::use(static_cast<int> (ShortMsgItem::INITIAL)),
            soci::use(groupId),
            soci::use(n);
    session_.session() << "unlock tables";
    return 0;
}

void ShortMsgItemDao::loadTestData(int n, int groupId)
{
    session_.session() << "truncate msg_items";
    for (int i=0;i<n;i++)
    {
        session_.session()<<"insert into msg_items(group_id, xid, to_addr, from_addr, insert_date, status, handler, last_update) "
                "values(:group_id, 0, '1234567', '987654', CURRENT_TIMESTAMP(), 0, '', CURRENT_TIMESTAMP() )", soci::use(groupId);
    }
}